/*
05-树9 Huffman Codes
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "../base/Huffman.c"

#include "../base/Tree-Traversal-Recursive.c"

/* current ==========================================*/
#define MaxSize 65

// 比较两个节点，负数 - e1 < e2; 0 - e1 == e2; 正数 - e1 > e2
int compareHeapNode(HeapElementType e1, HeapElementType e2) {
    if (e2->data.weight > e1->data.weight) {
        return 1;
    } else if (e2->data.weight < e1->data.weight) {
        return -1;
    } else {
        return 0;
    }
}

// 检查前缀
int checkPrefix(char code[][MaxSize], int n){
    int length;
    for(int i=0; i<n; i++){
        for (int j=i+1; j<n; j++){
            length = strlen(code[i]) < strlen(code[j]) ? strlen(code[i]) : strlen(code[j]);
            if (strncmp(code[i], code[j], length) == 0)
                return 0;
        }
    }
    return 1;
}

int check(int n, int wpl, int* f, char code[][MaxSize]) {
    // 检查wpl是否正确
    int s_wpl = 0;
    for (int i = 0; i<n; i++){
        s_wpl += strlen(code[i]) * f[i];
    }
    if (wpl != s_wpl) {
        return 0;
    }
    return checkPrefix(code, n);
}

int main() {
    int n, f[MaxSize];
    scanf("%d", &n);
    Heap* minHeap = createHeap(n, compareHeapNode);
    for (int i=0; i<n; i++) {
        char c[10];
        scanf("%s %d", c, &f[i]);
        // printf("c=%s, f=%d\n", c, f);
        HuffmanNode hfNode = createHuffmanNode(c, f[i]);
        HeapElementType node = createTreeNode(hfNode);
        insertHeap(minHeap, node);
    }
    Tree huffman = createHuffmanFromMinHeap(minHeap);
    freeHeap(minHeap);
    // printHuffman(huffman);
    // printf("\n");
    int wpl = calHuffmanWPL(huffman, 0);
    // printf("wpl = %d\n", wpl);
    calHuffmanCode(huffman);
    preorderTraversal(huffman);
    freeTree(huffman);

    int m;
    scanf("%d\n", &m);
    // printf("m=%d\n", m);
    for (int j=0; j<m; j++) {
        char code[MaxSize][MaxSize];
        for (int i=0; i<n; i++) {
            char c[4];
            scanf("%s %s", c, code[i]);
            // printf("c = %s, code = %s\n", c, code[i]);
        }
        if (check(n, wpl, f, code)) {
            printf("Yes\n");
        } else {
            printf("No\n");
        }
    }
    return 0;
}
